package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.bean.Employee;
import com.itheima.reggie.bean.PageParam;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //修改员工状态
    @Override
    public int update(Employee employee, long employeeId) {
        //手动补充信息
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(employeeId);

        return employeeMapper.updateById(employee);
    }

    //员工分页模糊查询
    @Override
    public IPage<Employee> findPage(PageParam pageParam) {
        //执行查询
        IPage<Employee> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        //设置模糊查询条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(pageParam.getName() != null, Employee::getName, pageParam.getName());

        return employeeMapper.selectPage(page, lqw);
    }

    //添加员工
    @Override
    public int add(Employee employee, long employeeId) {
        //需要手动补充数据
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);

        return employeeMapper.insert(employee);
    }

    //登录业务逻辑代码
    @Override
    public Employee login(Employee employee) {
        //设置登录用户和密码条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());

        //用户登录进来时进行加密
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        lqw.eq(Employee::getPassword, password);

        //追加用户的状态权限登录
        lqw.eq(Employee::getStatus, 1);
        return employeeMapper.selectOne(lqw);
    }
}
